package com.hyt.it.ogt.ksmonitor.statistics.redis;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱振宇
 * @since 2022/11/14
 */
@Component
@ConditionalOnClass(RedisTemplate.class)
public class BaseRedisTemplateService {

    @Resource
    private RedisTemplate redisTemplate;

    public String buildKey(String prefix, int[] index, Object[] args) {
        StringBuilder key = new StringBuilder(prefix);
        for (int i : index) {
            if (i >= args.length) {
                // 下标大于等于 参与列表的长度，获取不到值
                throw new ArrayIndexOutOfBoundsException("RedisInterceptor index : " + i + "大于方法的参与列表 ");
            }
            key.append(args[i]).append("_");
        }
        return key.deleteCharAt(key.length() - 1 ).toString();
    }

    public String buildKeyWithEqualSignal(int[] index, Object[] args) {
        StringBuilder key = new StringBuilder();
        for (int i : index) {
            if (i >= args.length) {
                // 下标大于等于 参与列表的长度，获取不到值
                throw new ArrayIndexOutOfBoundsException("RedisInterceptor index : " + i + "大于方法的参与列表 ");
            }
            key.append(args[i]).append(":");
        }
        return key.deleteCharAt(key.length() - 1).indexOf(":") >= 0 && index.length > 1
                ? key.replace(key.lastIndexOf(":"), key.lastIndexOf(":") + 1, "_").toString() : key.toString();
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public Object getAndSet(String key, Object value) {
        return redisTemplate.opsForValue().getAndSet(key, value);
    }

    public void set(String key, Object val, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, val, timeout, unit);
    }

    public Boolean setIfAbsent(String key, Object val) {
        return redisTemplate.opsForValue().setIfAbsent(key, val);
    }

    public Boolean setIfAbsent(String key, Object val, long timeout, TimeUnit unit) {
        return redisTemplate.opsForValue().setIfAbsent(key, val, timeout, unit);
    }

    public Boolean setIfPresent(String key, Object val, long timeout, TimeUnit unit) {
        return redisTemplate.opsForValue().setIfPresent(key, val, timeout, unit);
    }

    public void increment(String key) {
        redisTemplate.opsForValue().increment(key);
    }

    public void increment(String key, long num) {
        redisTemplate.opsForValue().increment(key, num);
    }

    public void decrement(String key) {
        redisTemplate.opsForValue().decrement(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
